import execjs
import requests
from lxml import etree


def one():
    response = session.get(url, headers=headers)
    print("第一次响应码=>", response.status_code)
    print("第一次cookie值：", session.cookies)
    obj = etree.HTML(response.text)  # type: ignore
    ts_src = 'https://sugh.szu.edu.cn' + obj.xpath('//script[1]/@src')[0]
    ts_code = requests.get(ts_src, headers=headers).text
    content_code = obj.xpath('//meta[2]/@content')[0]
    func_code = obj.xpath('//script[2]/text()')[0]
    two(func_code, content_code, ts_code)


def two(func_code, content_code, ts_code):
    with open('main.js', encoding='utf-8') as f:
        code = f.read().replace('func_code', func_code).replace('content_code', content_code).replace('ts_code',
                                                                                                      ts_code)
    # print(code)
    res = execjs.compile(code).call('get_cookie')
    # print(res)
    res = res.split(';')[0].split('=')
    print(res)
    session.cookies[res[0]] = res[1]
    headers['Referer'] = url
    print("第二次cookie值：", session.cookies)
    response = session.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    print("第二次响应码=>", response.status_code)
    parse(response.text)


def parse(text):
    html = etree.HTML(text)
    li_list = html.xpath("//ul[@id='zoom']/li")
    domain = "https://sugh.szu.edu.cn"
    for l in li_list:
        title = l.xpath(".//a[@class='dy_title']/text()")[0].strip()
        date = l.xpath(".//div[@class='meta']/span[@class='time']/text()")[0].strip()
        url = l.xpath(".//a[last()]/@href")[0].strip()
        print(title, date, domain + url)


if __name__ == '__main__':
    url = 'https://sugh.szu.edu.cn/Html/News/Columns/7/Index.html'
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
        'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Microsoft Edge";v="120"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }
    session = requests.session()
    one()
